<?php 

function result_to_csv( $datas , $headers = false ){
	$contents = '';
	
	if($headers){
		$total_header = count($headers);
		$i = 1;
		foreach($headers as $header){
			if($i == $total_header)
				$contents .= '"'. addslashes($header) .'"'."\n";
				
			else
				$contents .= '"'. addslashes($header) .'",'; 
			$i++;			
		}
	}
	
	if(is_array($datas)){
		foreach($datas as $datarow){
			$t = count($datarow);
			$n = 1;
			foreach($datarow as $field => $label){ 
				if($n == $t)
				$contents.= '"'. addslashes($label) .'"'."\n"; 
				else
				$contents.= '"'. addslashes($label) .'",'; 
				$n++;
			}  
		} 
	}
	
	return $contents;
	
}

function download_csv($contents , $file = false){ 
	if(!$file)	$file = substr(md5(rand(0,100)) , rand(0,20 ) ,9).rand( 1000 , 9000 ).'.csv';
	elseif(strtolower(end( explode(".",$file) )) <> 'csv') $file = substr( md5(rand(0,100) ) , rand(0,20 ) , 9 ) . rand( 1000 , 9000 ).'.csv';
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Content-Type: application/csv");
	header( "Content-Disposition: attachment; filename=".basename($file));
	header( "Content-Description: File Transfer");
	echo $contents;
	exit;
}



function data_karyawan_list_csv( ){

	$header_karyawan = array(
		'Nama' , 
		'NIK' ,  
		'Usia' ,  
		'Kelamin' ,   
		'No Seluler' ,   
		'Status' ,   
		'Agama' ,   
		'Catatan' ,   
	);
	$np=1;
	$row = array();
	$query = "SELECT * FROM karyawan a INNER JOIN biodata b ON a.biodata_id = b.biodata_id
	ORDER BY karyawan_id ASC  ";
	$result = my_query($query);
	while ($kar = my_fetch_array($result) ){ 
		$row[] = array( 
			'nama'=>  	strtoupper($kar['nama']), 
			'nik'=>  	strtoupper($kar['nik']),
			'usia'=>   	getage($kar['tanggal_lahir']),
			'kelamin'=>	ucfirst($kar['kelamin'])   ,	
			'seluler'=> strtoupper($kar['telepon_mobile']),  
			'status'=> 	strtoupper($kar['marital']),  
			'agama'=> 	strtoupper($kar['agama']),   
			'catatan'=> strtoupper($kar['catatan']),  
		); 
		$np++;
	} 
	$te = result_to_csv( $row , $header_karyawan);  
	download_csv($te);
}